package fr.unice.polytech.chord.samples.commands;

import java.math.BigInteger;

import org.objectweb.proactive.ActiveObjectCreationException;
import org.objectweb.proactive.core.node.NodeException;

import fr.unice.polytech.chord.core.ChordFactory;
import fr.unice.polytech.chord.core.ChordNode;
import fr.unice.polytech.chord.core.Key;
import fr.unice.polytech.chord.core.Tracker;
import fr.unice.polytech.chord.samples.managers.Manager;

/**
 * @author Laurent Pellegrino
 * 
 * @version 10/30/2009
 */
public class JoinCommand extends Command {

	/**
	 * Constructor.
	 * 
	 * @param manager
	 *            the manager that will execute this command.
	 */
	public JoinCommand(Manager manager) {
		super(
				manager,
				"Inserts a new chord node with the specified key on the overlay",
				new String[] { "join", "j" }, new String[] { "key" });
	}

	/**
	 * {@inheritDoc}
	 */
	public void execute(String... args) {
		if (args.length == 1) {
			ChordNode node = null;
			try {
				node = ChordFactory.newActiveChordNode(Integer
						.parseInt(args[0]));
			} catch (ActiveObjectCreationException e) {
				e.printStackTrace();
			} catch (NodeException e) {
				e.printStackTrace();
			} catch (Exception e) {
				super.printInfo("Key argument must be a number");
				return;
			}
			Tracker tracker = super.getManager().getTracker();
			if (tracker.getNumberOfPeersManaged() > 0
					&& tracker.getRandomPeer().findSuccessor(node.getKey())
							.getKey().compareTo(node.getKey()) == 0) {
				super.printInfo("A node with key '" + node.getKey()
						+ "' already exist, operation is snubbed");
			} else {
				tracker.addOnNetwork(node);

				Key key = new Key(new BigInteger(args[0]));
				super.printInfo("Node with key " + key
						+ " has joined the network");
			}
		} else {
			super
					.printInfo("Join operation must have one argument which is the key of the new chord node.");
		}
	}
}
